package com.study.algorithm.sort;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RadixSort {
    public static int[] sort(int[] nums) {
        if (nums.length < 2) {
            return nums;
        }
        int n = 0;
        int max = nums[0];
        for (int num : nums) {
            if (num > max) {
                max = num;
            }
        }
        while (max > 0) {
            max = max / 10;
            n++;
        }
        for (int i = 0; i < n; i++) {
            List<List<Integer>> radix = new ArrayList<>();
            for (int j = 0; j < 10; j++) {
                radix.add(new ArrayList<>());
            }
            for (int j = 0; j < nums.length; j++) {
                int index = (nums[j] / ((int) Math.pow(10, i))) % 10;
                radix.get(index).add(nums[j]);
            }
            int idx = 0;
            for (List<Integer> items : radix) {
                for (Integer item : items) {
                    nums[idx++] = item;
                }
            }
        }
        return nums;
    }

    public static void main(String[] args) {
        int[] nums = {1, 5, 8, 7, 1, 2, 5, 4, 66, 5, 84, 5, 110, 4, 5, 4};
        sort(nums);
        System.out.println("nums = " + Arrays.toString(nums));
    }
}
